using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using Volo.Abp.DependencyInjection;

namespace Joy.Erp.Ufida.Pmc
{
    /// <summary>
    /// 需求订单缓存服务实现
    /// </summary>
    public class DemandOrderCacheService : IDemandOrderCacheService, ISingletonDependency
    {
        private const string CacheKey = "DemandOrders_Cache";
        private readonly IMemoryCache _memoryCache;

        public DemandOrderCacheService(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }

        public Task SetCacheAsync(List<DemandOrderDto> demandOrders)
        {
            var cacheOptions = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromHours(2)) // 2小时未访问则过期
                .SetAbsoluteExpiration(TimeSpan.FromHours(8)); // 8小时绝对过期

            _memoryCache.Set(CacheKey, demandOrders, cacheOptions);

            return Task.CompletedTask;
        }

        public Task<List<DemandOrderDto>> GetAllAsync()
        {
            if (_memoryCache.TryGetValue(CacheKey, out List<DemandOrderDto> demandOrders))
            {
                return Task.FromResult(demandOrders);
            }

            return Task.FromResult(new List<DemandOrderDto>());
        }

        public async Task<List<DemandOrderDto>> GetPagedListAsync(int skipCount, int maxResultCount)
        {
            var allOrders = await GetAllAsync();
            return allOrders.Skip(skipCount).Take(maxResultCount).ToList();
        }

        public async Task<int> GetCountAsync()
        {
            var allOrders = await GetAllAsync();
            return allOrders.Count;
        }

        public async Task<bool> UpdateAsync(
            string docNo,
            string docType,
            DemandOrderDto demandOrder
        )
        {
            var allOrders = await GetAllAsync();

            // 查找要更新的订单
            var existingOrder = allOrders.FirstOrDefault(x =>
                x.DocNo == docNo && x.DocType == docType
            );

            if (existingOrder == null)
            {
                return false;
            }

            // 更新订单数据（保留主键，更新其他字段）
            var index = allOrders.IndexOf(existingOrder);
            demandOrder.DocNo = docNo; // 确保主键不变
            demandOrder.DocType = docType; // 确保主键不变
            allOrders[index] = demandOrder;

            // 更新缓存
            await SetCacheAsync(allOrders);

            return true;
        }

        public Task ClearAsync()
        {
            _memoryCache.Remove(CacheKey);
            return Task.CompletedTask;
        }

        public Task<bool> ExistsAsync()
        {
            var exists = _memoryCache.TryGetValue(CacheKey, out _);
            return Task.FromResult(exists);
        }
    }
}
